﻿using XiangziProjectTemplete.Core.Common.HttpContextUser;
using XiangziProjectTemplete.Core.Extensions.Others;
using XiangziProjectTemplete.Core.IServices;
using XiangziProjectTemplete.Core.Model;
using XiangziProjectTemplete.Core.Model.CommonModel;
using XiangziProjectTemplete.Core.Model.Models;
using XiangziProjectTemplete.Core.Model.ParamModels;
using XiangziProjectTemplete.Core.Utility;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Threading.Tasks;
using System;

namespace XiangziProjectTemplete.Core.Api.Controllers
{
    /// <summary> 
    /// 物料管理 
    /// </summary> 
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize(Permissions.Name)]
    public class Base_MaterialController : ControllerBase
    {
        private readonly IBase_MaterialServices _Base_MaterialServices;
        private readonly IUser _user;
        private readonly ILogger<Base_MaterialController> _logger;

        public Base_MaterialController(IBase_MaterialServices Base_MaterialServices, IUser user, ILogger<Base_MaterialController> logger)
        {
            _Base_MaterialServices = Base_MaterialServices;
            _user = user;
            _logger = logger;
        }

        /// <summary> 
        /// 分页获取物料管理列表 
        /// </summary> 
        /// <param name="param">筛选条件</param> 
        /// <returns>获取结果</returns> 
        [HttpPost]
        public async Task<MessageModel<PageModel<Base_Material>>> Get([FromBody] Base_MaterialParam param)
        {
            if (string.IsNullOrEmpty(param.searchVal) || string.IsNullOrWhiteSpace(param.searchVal))
            {
                param.searchVal = string.Empty;
            }

            var whereConditions = WhereConditionsExtensions.GetWhereConditions<Base_Material, Base_MaterialParam>(param);
            if (!whereConditions.IsSuccess)
            {
                return new MessageModel<PageModel<Base_Material>>()
                {
                    msg = whereConditions.ErrMsg,
                    success = false,
                    response = null
                };
            }
            var data = await _Base_MaterialServices.QueryPage(whereConditions.data, param.page, param.pageSize, " ModifyTime desc ");
            return new MessageModel<PageModel<Base_Material>>()
            {
                msg = "获取成功",
                success = true,
                response = data
            };

        }

        /// <summary> 
        /// 获取单个物料管理 
        /// </summary> 
        /// <param name="id">主键</param> 
        /// <returns>获取结果</returns> 
        [HttpGet]
        public async Task<MessageModel<Base_Material>> Get(int id = 0)
        {
            return new MessageModel<Base_Material>()
            {
                msg = "获取成功",
                success = true,
                response = await _Base_MaterialServices.QueryById(id)
            };
        }

        /// <summary> 
        /// 新增物料管理 
        /// </summary> 
        /// <param name="request">要新增的物料管理对象</param> 
        /// <returns></returns> 
        [HttpPost]
        public async Task<MessageModel<string>> Post([FromBody] Base_Material request)
        {
            try
            {
                #region 验证 
                MessageModel<string> retBody = null;
                retBody = ValidateDataHelper.CommonValidateIsNULL<Base_Material, string>(request);
                if (retBody != null)
                {
                    return retBody;
                }

                List<ValidateModel> columnsList = null;
                columnsList = new List<ValidateModel>() {
                     //new ValidateModel(){ ChinaName="入库时间",PropertyName="InStoreTime",DataType=typeof(DateTime),IsNullable=true },
                     //new ValidateModel(){ ChinaName="修改时间",PropertyName="ModifyTime",DataType=typeof(DateTime),IsNullable=true },

                };
                retBody = ValidateDataHelper.CommonValidate<Base_Material, string>(request, columnsList);
                if (retBody != null)
                {
                    return retBody;
                }
                #endregion

                request.CreateTime = request.ModifyTime = DateTime.Now;
                request.CreateBy = request.ModifyBy = _user.Name;
                request.CreateId = request.ModifyId = _user.ID;
                request.OperationRemark = "添加";
                var id = await _Base_MaterialServices.Add(request);
                var success = id > 0;

                if (success)
                {
                    return MessageModel<string>.Success("添加成功", id.ObjToString());
                }
                return MessageModel<string>.Fail("添加失败");
            }
            catch (Exception ex)
            {
                _logger.LogError("新增物料管理出现异常,ex:" + JsonConvert.SerializeObject(ex));
                return MessageModel<string>.Fail("新增物料管理出现异常:" + ex.Message);
            }
        }

        /// <summary> 
        /// 更新物料管理 
        /// </summary> 
        /// <param name="request">要更新的物料管理对象</param> 
        /// <returns>更新结果</returns> 
        [HttpPut]
        public async Task<MessageModel<string>> Put([FromBody] Base_Material request)
        {
            try
            {
                #region 验证 
                MessageModel<string> retBody = null;
                retBody = ValidateDataHelper.CommonValidateIsNULL<Base_Material, string>(request);
                if (retBody != null)
                {
                    return retBody;
                }

                List<ValidateModel> columnsList = null;
                columnsList = new List<ValidateModel>()
                {
                                         new ValidateModel(){ ChinaName="主键",PropertyName="Id" },
                     //new ValidateModel(){ ChinaName="入库时间",PropertyName="InStoreTime",DataType=typeof(DateTime),IsNullable=true },
                     //new ValidateModel(){ ChinaName="修改时间",PropertyName="ModifyTime",DataType=typeof(DateTime),IsNullable=true },

                };
                retBody = ValidateDataHelper.CommonValidate<Base_Material, string>(request, columnsList);
                if (retBody != null)
                {
                    return retBody;
                }
                #endregion

                var dbObj = await _Base_MaterialServices.QueryById(request.Id);
                if (dbObj == null)
                {
                    return MessageModel<string>.Fail("数据不存在!");
                }

                request.ModifyTime = DateTime.Now;
                request.ModifyBy = _user.Name;
                request.ModifyId = _user.ID;
                request.OperationRemark = "更新";
                var success = await _Base_MaterialServices.Update(request);

                if (success)
                {
                    return MessageModel<string>.Success("更新成功", request.Id.ObjToString());
                }
                return MessageModel<string>.Fail("更新失败");
            }
            catch (Exception ex)
            {
                _logger.LogError("更新物料管理出现异常,ex:" + JsonConvert.SerializeObject(ex));
                return MessageModel<string>.Fail("更新物料管理出现异常:" + ex.Message);
            }
        }

        /// <summary> 
        /// 删除物料管理 
        /// </summary> 
        /// <param name="id">主键</param> 
        /// <returns>删除结果</returns> 
        [HttpDelete]
        public async Task<MessageModel<string>> Delete(int id = 0)
        {
            try
            {
                var data = new MessageModel<string>();
                if (id > 0)
                {
                    var detail = await _Base_MaterialServices.QueryById(id);
                    if (detail != null)
                    {
                        data.success = await _Base_MaterialServices.DeleteById(detail.Id);
                        if (data.success)
                        {
                            data.msg = "删除成功";
                            data.response = detail?.Id.ObjToString();
                        }
                    }
                    else
                    {
                        return MessageModel<string>.Fail("数据不存在!");
                    }
                }
                else
                {
                    data.success = false;
                    data.msg = "删除失败,物料管理不存在";
                }
                return data;
            }
            catch (Exception ex)
            {
                _logger.LogError("删除物料管理出现异常,ex:" + JsonConvert.SerializeObject(ex));
                return MessageModel<string>.Fail("删除物料管理出现异常:" + ex.Message);
            }
        }

        /// <summary> 
        /// 逻辑删除物料管理 
        /// </summary> 
        /// <param name="id">主键</param> 
        /// <returns>删除结果</returns> 
        [HttpDelete]
        public async Task<MessageModel<string>> LogicDelete(int id = 0)
        {
            try
            {
                var data = new MessageModel<string>();
                if (id > 0)
                {
                    var detail = await _Base_MaterialServices.QueryById(id);
                    if (detail != null)
                    {
                        detail.ModifyTime = DateTime.Now;
                        detail.ModifyBy = _user.Name;
                        detail.ModifyId = _user.ID;
                        detail.IsDeleted = true;
                        detail.OperationRemark = "删除";
                        data.success = await _Base_MaterialServices.Update(detail);
                        if (data.success)
                        {
                            data.msg = "删除成功";
                            data.response = detail?.Id.ObjToString();
                        }
                    }
                }
                else
                {
                    data.success = false;
                    data.msg = "删除失败,数据不存在";
                }
                return data;
            }
            catch (Exception ex)
            {
                _logger.LogError("逻辑删除物料管理出现异常,ex:" + JsonConvert.SerializeObject(ex));
                return MessageModel<string>.Fail("逻辑删除物料管理出现异常:" + ex.Message);
            }
        }
    }
}
